﻿package Classes{
	import flash.display.*;
	import flash.text.*;
	import flash.events.*;
	import flash.utils.*;
	import flash.ui.*;
	import flash.filters.DropShadowFilter;
	
	import Classes.Missions.*;
	import Classes.Maps.*;
	import Classes.Utils.*;
	import Classes.Player.*;
	import Classes.Layers.*;
	import Classes.Elements.*;
	import Classes.Enemies.Emplacements.*;
	import Classes.Enemies.Aero.*;
	import Classes.Explode.*;
	import Classes.Bonus.*;
	import Classes.data.DataProcess;

	public class ThunderDoc extends MovieClip {
		private const sceneWidth:int = Maps.sceneWidth;
		private const sceneHeight:int = Maps.sceneHeight;
		private const numTile:int = Maps.numTile;
		private const stagespeed:int = GameSettings.stagespeed;
		//入口得到的flashvars数据
		private var posturl:String;         //提交数据的接口
		private var passid:String;         //玩家帐号ID
		private var accountname:String;     //玩家帐号
		private var gameid:String;           //游戏ID
		private var gamemode:String;        //游戏模式 0普通模式 1挑战模式
		private var begintime:String;        //游戏开始时间
		private var rivalpassid:String;      //对手帐号ID   (普通模式不需要)
		private var rivalaccountname:String; //对手帐号     (普通模式不需要)
		private var rivallevel:String;       //对手排名     (普通模式不需要)
		private var rivalscore:Number;		 //对手的分数   (普通模式不需要)
		
		//数据初始化容器
		private var dataProcess:DataProcess;
		//初始化标志
		private var dataFlag:Boolean = true;
		//分数
		private var score:int;
		//总分数
		private var totalscore:int;
		//生命计数
		private var numRemain:int;
		//结束计时器
		private var endTimer:Timer;
		//重置计时器
		private var resetTimer:Timer;
		//下一关计时器
		private var nextTimer:Timer;
		//当前关
		private var crtMission:int;
		//分值奖励次数
		private var numBonusTimes:int;
		//当前位置
		private var crtPosition:int;
		//绝对位置
		private var absPosition:int;
		//当前敌人指针
		private var crtEnemy:int;
		//场景层
		private var scene:MovieClip;
		//遮罩层
		private var scenemask:Sprite;
		//玩家信息
		private var playerInfo:PlayerInfo;
		//天空层
		private var skyLayer:Layer;
		//玩家层
		private var playerLayer:Layer;
		//子弹层
		private var bulletLayer:Layer;
		//地面层
		private var groundLayer:Layer;
		//奖励层
		private var bonusLayer:Layer;
		//普通层
		private var commonLayer:Layer;
		//地图对象
		private var bgMap:Maps;
		//键盘设置对象
		private var ks:KeySets;
		//玩家角色
		private var fighter:Fighter;
		//敌人数组
		private var aEnemies:Array;
		//玩家数组
		private var aPlayers:Array;
		//移动范围
		private var moverange = [-30,sceneWidth + 30,-30,sceneHeight+30];
		private var deltarange = [-180,sceneWidth + 180,-30,sceneHeight+30];
		//构造函数
		public function ThunderDoc() {
			//得到flashvars变量数据
			posturl=stage.loaderInfo.parameters["posturl"];						//提交数据的接口
			passid=stage.loaderInfo.parameters["passid"];          				//玩家帐号ID
			accountname=stage.loaderInfo.parameters["accountname"];      		//玩家帐号
			gameid=stage.loaderInfo.parameters["gameid"];              			//游戏ID
			gamemode=stage.loaderInfo.parameters["gamemode"];            		//游戏模式 0普通模式 1挑战模式
			begintime=stage.loaderInfo.parameters["begintime"];         		//游戏开始时间
			rivalpassid=stage.loaderInfo.parameters["rivalpassid"];        		//对手帐号ID   (普通模式不需要)
			rivalaccountname=stage.loaderInfo.parameters["rivalaccountname"];   //对手帐号     (普通模式不需要)
			rivallevel=stage.loaderInfo.parameters["rivallevel"];          		//对手排名     (普通模式不需要)
	  		rivalscore=stage.loaderInfo.parameters["rivalscore"]; 				//对手的分数
			
			//加载和梦天堂网络log
			loadingPlay();
			//加载配置文件
			dataProcess = new DataProcess();
			addChildAt(dataProcess, numChildren);
			dataProcess.cfgInit();
			//dataProcess.addEventListener(Event.COMPLETE, dataProcessHandler);
			
			//初始化数据			
			stop();
			crtMission = 0;
			numBonusTimes = 1;
			mcHelp.visible = false;
			mcEndInfo.visible = false;
			mcGameInterval.x = 102;
			mcGameInterval.visible = false;
			btnStart.addEventListener(MouseEvent.CLICK,btnStart_Click);
			btnHelp.addEventListener(MouseEvent.CLICK,btnHelp_Click);
		
		}
		
		private function dataProcessHandler(e:Event):void {
			dataFlag = true;
		}
		
		private function loadingPlay():void {
			loading.addEventListener("loadedEvent",loadedHandler);
		}
		
		private function loadedHandler(e:Event):void {	
			//btnStart.addEventListener(MouseEvent.CLICK,btnStart_Click);
			//btnHelp.addEventListener(MouseEvent.CLICK,btnHelp_Click);
		}
		
		//开始游戏按钮
		private function btnStart_Click(e:MouseEvent):void {
			gotoAndStop("Start");
			mcGates.gotoAndPlay("open");
			initGame();
		}
		//帮助按钮
		private function btnHelp_Click(e:MouseEvent):void {
			mcHelp.visible = !mcHelp.visible;
		}
		//重新开始按钮
		private function btnRestart_Click(e:MouseEvent):void {
			gotoAndStop("Start");
			mcGates.gotoAndPlay("open");
			//btnRestart.visible = false;
			initGame();
		}
		//游戏初始化
		private function initGame():void {
			mcHelp.visible = false;
			mcEndInfo.visible = false;
			mcGameInterval.visible = false;
			numRemain = GameSettings.StartNum - 1;

			score = 0;
			totalscore = 0;
			crtEnemy = 0;
			aEnemies = [];
			aPlayers = [];

			nextTimer = new Timer(2000,4);
			resetTimer = new Timer(1000);
			endTimer = new Timer(1800);
			nextTimer.addEventListener(TimerEvent.TIMER,nextMission);
			resetTimer.addEventListener(TimerEvent.TIMER,resetPlayer);
			endTimer.addEventListener(TimerEvent.TIMER,gameOver);

			ks = new KeySets(Keyboard.LEFT,Keyboard.RIGHT,Keyboard.UP,Keyboard.DOWN,88,Keyboard.SPACE);
			PopKeys.initStage(stage);

			playerInfo = new PlayerInfo();
			playerInfo.x = 0;
			playerInfo.y = 480;
			addChildAt(playerInfo,0);
			scene = new MovieClip();
			addChildAt(scene,0);

			initMission();
			createMask();
			createBG();
			createGroundLayer();
			createCommonLayer();
			createBulletLayer();
			createBonusLayer();
			createSkyLayer();
			createPlayerLayer();
			createFighter();

			scene.addEventListener(Event.ENTER_FRAME,sceneEnterFrame);
		}
		//初始化关卡
		private function initMission():void {
			crtEnemy = 0;
			crtPosition = sceneHeight;
			absPosition = crtPosition;
			if (fighter) {
				fighter.reset();
			}
		}
		//创建背景图
		private function createBG():void {
			bgMap = new Maps(Missions.aMission[crtMission].map);
			scene.addChildAt(bgMap.bmpBG,0);
		}
		//创建遮罩
		private function createMask():void {
			scenemask = new Sprite();
			scenemask.graphics.beginFill(0x000000);
			scenemask.graphics.drawRect(0,0,sceneWidth,sceneHeight+20);
			scenemask.graphics.endFill();
			addChild(scenemask);
			this.mask = scenemask;
		}
		//创建玩家角色层
		private function createPlayerLayer():void {
			playerLayer = new Layer(Layer.PLAYER);
			playerLayer.useShadow = true;
			scene.addChild(playerLayer);
		}
		//创建地面层
		private function createGroundLayer():void {
			groundLayer = new Layer(Layer.GROUND);
			groundLayer.useShadow = true;
			scene.addChild(groundLayer);
		}
		//创建天空层
		private function createSkyLayer():void {
			skyLayer = new Layer(Layer.SKY);
			skyLayer.useShadow = true;
			scene.addChild(skyLayer);
		}
		//创建奖励层
		private function createBonusLayer():void {
			bonusLayer = new Layer(Layer.BONUS);
			bonusLayer.useShadow = true;
			scene.addChild(bonusLayer);
		}
		//创建子弹层
		private function createBulletLayer():void {
			bulletLayer = new Layer(Layer.BULLET);
			bulletLayer.useShadow = true;
			scene.addChild(bulletLayer);
		}
		//创建通用层
		private function createCommonLayer():void {
			commonLayer = new Layer(Layer.EXPLODE);
			commonLayer.useShadow = false;
			scene.addChild(commonLayer);
		}
		//创建玩家
		private function createFighter():void {
			if (fighter) {
				playerLayer.removeChild(fighter);
				fighter = null;
			}
			fighter = new Fighter();
			fighter.dimension = playerLayer;
			fighter.bulletLayer = bulletLayer;
			fighter.aTargets = aEnemies;
			fighter.x = sceneWidth/2;
			fighter.y = sceneHeight - fighter.height;
			fighter.keySets = ks;
			aPlayers.push(fighter);
			playerLayer.addChild(fighter);
		}
		//游戏进行
		private function sceneEnterFrame(e:Event):void {
			crtPosition += stagespeed;
			createUnit();
			bgMap.scrollBg(crtPosition);
			setPlayerInfo();
			removeElement(bulletLayer);
			removeElement(commonLayer);
			removeEnemies();
			removePlayer();
			removeBonus();
		}
		//设置玩家信息
		private function setPlayerInfo():void {
			if (!fighter) {
				playerInfo.hp = 0;
			} else {
				playerInfo.hp = fighter.hp;
				playerInfo.remains = numRemain;
				playerInfo.numRockets = fighter.count;
				playerInfo.energy = fighter.energy;
				score = fighter.score;
				playerInfo.score = totalscore + score;
				if (playerInfo.score>numBonusTimes * GameSettings.ScoreBonus) {
					numBonusTimes++;
					numRemain++;
				}
				playerInfo.mission = Missions.aMission[crtMission].mission;
			}
		}
		//清除奖励元素
		private function removeBonus():void {
			for (var i:int=0; i<bonusLayer.numChildren; i++) {
				var el:Bonus = bonusLayer.getChildAt(i) as Bonus;
				if (el.erasable) {
					el.remove();
					bonusLayer.removeChildAt(i);
					el.erasable = false;
					el = null;
					continue;
				}
			}
		}
		//按层清除元素
		private function removeElement(layer:Layer):void {
			for (var i:int=0; i<layer.numChildren; i++) {
				var el:BasicElement = layer.getChildAt(i) as BasicElement;
				if (el.erasable) {
					if (el.explodeable) {
						var ex:Explode = createExplode(layer.layerType);
						ex.x = el.x;
						ex.y = el.y;
						ex.explode();
						commonLayer.addChild(ex);
					}
					el.remove();
					layer.removeChild(el);
					el=null;
				}
			}
		}
		//清除敌方目标
		private function removeEnemies():void {
			for (var i:int=0; i<aEnemies.length; i++) {
				var el:Element = aEnemies[i] as Element;
				if (el.erasable) {
					if (el.explodeable) {
						var ex:Explode = createExplode(el.dimension.layerType);
						ex.x = el.x;
						ex.y = el.y;
						if (fighter) {
							fighter.score += el.score;
						}
						ex.explode();
						commonLayer.addChild(ex);
					}
					aEnemies.splice(i,1);
					el.remove();
					el.dimension.removeChild(el);
					el=null;
				}
			}
			if (!aEnemies.length && crtEnemy== Missions.aMission[crtMission].units.length) {
				crtEnemy++;
				fighter.hurtable = false;
				mcGates.gotoAndPlay("close");
				nextTimer.start();
			}
		}
		//清除玩家角色
		private function removePlayer():void {
			if (!fighter) {
				return;
			}
			if (fighter.erasable) {
				var ex:Explode = createExplode(playerLayer.layerType);
				ex.x = fighter.x;
				ex.y = fighter.y;
				ex.explode();
				commonLayer.addChild(ex);
				playerLayer.removeChild(fighter);
				aPlayers.pop();
				totalscore += score;
				fighter.remove();
				fighter = null;
				numRemain--;
				if (numRemain >= 0) {
					resetTimer.start();
				} else {
					mcGates.gotoAndPlay("close");
					endTimer.start();
				}
			}
		}
		//重置玩家
		private function resetPlayer(e:TimerEvent):void {
			createFighter();
			resetTimer.reset();
		}
		//下一关
		private function nextMission(e:TimerEvent):void {
			if(nextTimer.currentCount==1 && fighter){
				mcGameInterval.visible = true;
				mcGameInterval.txtMission.text = Missions.aMission[crtMission].mission;				
				totalscore += fighter.count*20 + numRemain * 500 + (fighter.numGuns-2)*50;
				mcGameInterval.txtScore.text = playerInfo.score;
				mcGameInterval.txtGuns.text = (fighter.numGuns - 2).toString() + "x 50+";
				mcGameInterval.txtRemain.text = numRemain.toString() + "x 500+";
				mcGameInterval.txtRockets.text = fighter.count.toString() + " x 20+";
				fighter.fireable = false;
				fighter.x = sceneWidth/2;
				fighter.y = sceneHeight - fighter.height/2;
			}
			
			if(nextTimer.currentCount==3){
			
				crtEnemy = 0;
				crtMission++;
				if (crtMission==Missions.aMission.length) {
					crtMission = 0;
				}
				scene.removeChild(bgMap.bmpBG);
				for (var j:int=bonusLayer.numChildren-1; j>=0; j--) {
					var bl:Bonus = bonusLayer.getChildAt(j) as Bonus;
					bl.erasable = true;
				}
				bgMap = null;
				createBG();
				mcGates.gotoAndPlay("open");
				initMission();
				nextTimer.reset();
			
				mcGameInterval.visible = false;
			}
			

		}
		//游戏结束
		private function gameOver(e:TimerEvent):void {
			removeChild(scene);
			removeChild(scenemask);
			removeChild(playerInfo);
			scene.removeEventListener(Event.ENTER_FRAME,sceneEnterFrame);
			scene = null;
			scenemask = null;
			playerInfo = null;

			gotoAndStop("GameOver");
			for(var i=0;i<aEnemies.length;i++){
				aEnemies[i] = null;
			}
			mcEndInfo.visible = true;
			mcEndInfo.txtTotalScore.text = totalscore.toString();
			//btnRestart.visible = true;
			//btnRestart.addEventListener(MouseEvent.CLICK,btnRestart_Click);
			endTimer.reset();
			crtMission = 0;
			
			//提交分数
			mcEndInfo.btnsubmit.addEventListener(MouseEvent.CLICK,submitHandler);
		}
		
		private function submitHandler(e:MouseEvent):void {
			mcEndInfo.btnsubmit.removeEventListener(MouseEvent.CLICK,submitHandler);
			if (dataFlag) {
				dataProcess.submitData(posturl,totalscore,passid,accountname,gameid,gamemode,begintime,rivalpassid,rivalaccountname,rivallevel,rivalscore);
			}		
		}
		
		//创建爆炸效果
		private function createExplode(type:int):Explode {
			var ex:Explode;
			switch (type) {
				case Layer.PLAYER :
					ex = new Burst() as Explode;
					break;
				case Layer.BULLET :
					ex = new MiniExplode() as Explode;
					break;
				default :
					ex = new UnitExplode() as Explode;
					break;
			}
			return ex;
		}
		//创建单位
		private function createUnit():void {
			var relPosition:int = crtPosition-absPosition;
			if (crtEnemy > Missions.aMission[crtMission].units.length-1) {
				return;
			}
			if (relPosition == Missions.aMission[crtMission].units[crtEnemy].interval) {
				absPosition = crtPosition;
				createElement(Missions.aMission[crtMission].units[crtEnemy]);
				crtEnemy++;
			}
		}
		//创建各元素
		private function createElement(u:Unit):void {
			switch (u.unitType) {
					//空中目标
				case UnitType.Archer :
					var archer:Archer = new Archer();
					archer.dimension = skyLayer;
					archer.moverange = moverange;
					archer.aTargets = aPlayers;
					archer.aFriends = aEnemies;
					archer.createCarriee();
					archer.x = u.xpos;
					archer.y = u.ypos;
					archer.condition = u.condition;
					skyLayer.addChild(archer);
					aEnemies.push(archer);
					break;
				case UnitType.Buffalo :
					var buffalo:Buffalo = new Buffalo();
					buffalo.dimension = skyLayer;
					buffalo.bulletLayer = bulletLayer;
					buffalo.moverange = moverange;
					buffalo.aTargets = aPlayers;
					buffalo.x = u.xpos;
					buffalo.y = u.ypos;
					skyLayer.addChild(buffalo);
					aEnemies.push(buffalo);
					break;
				case UnitType.Delta :
					var dlt:Delta = new Delta();
					dlt.dimension = skyLayer;
					dlt.bulletLayer = bulletLayer;
					dlt.moverange = deltarange;
					dlt.aTargets = aPlayers;
					dlt.x = u.xpos;
					dlt.y = u.ypos;
					dlt.condition = u.condition;
					skyLayer.addChild(dlt);
					aEnemies.push(dlt);
					break;
				case UnitType.Pirate :
					var pirate:Pirate = new Pirate();
					pirate.dimension = skyLayer;
					pirate.bulletLayer = bulletLayer;
					pirate.moverange = moverange;
					pirate.aFriends = aEnemies;
					pirate.aTargets = aPlayers;
					pirate.x = u.xpos;
					pirate.y = u.ypos;
					skyLayer.addChild(pirate);
					aEnemies.push(pirate);
					break;

					//地面目标
				case UnitType.Cannon :
					var cannon:Cannon = new Cannon();
					cannon.dimension = groundLayer;
					cannon.bulletLayer = bulletLayer;
					cannon.aTargets = aPlayers;
					cannon.moverange = moverange;
					cannon.x = u.xpos;
					cannon.y = u.ypos;
					groundLayer.addChild(cannon);
					aEnemies.push(cannon);
					break;
				case UnitType.Flak :
					var flak:Flak = new Flak();
					flak.dimension = groundLayer;
					flak.bulletLayer = bulletLayer;
					flak.aTargets = aPlayers;
					flak.moverange = moverange;
					flak.x = u.xpos;
					flak.y = u.ypos;
					groundLayer.addChild(flak);
					aEnemies.push(flak);
					break;
				case UnitType.Karl :
					var karl:Karl = new Karl();
					karl.dimension = groundLayer;
					karl.bulletLayer = bulletLayer;
					karl.aTargets = aPlayers;
					karl.moverange = moverange;
					karl.x = u.xpos;
					karl.y = u.ypos;
					groundLayer.addChild(karl);
					aEnemies.push(karl);
					break;
				case UnitType.Rocketdrome :
					var rd:Rocketdrome = new Rocketdrome();
					rd.dimension = groundLayer;
					rd.bulletLayer = bulletLayer;
					rd.aTargets = aPlayers;
					rd.moverange = moverange;
					rd.x = u.xpos;
					rd.y = u.ypos;
					groundLayer.addChild(rd);
					aEnemies.push(rd);
					break;
					//奖励
				case UnitType.LifeBonus :
					var lb:LifeBonus = new LifeBonus();
					lb.dimension = bonusLayer;
					lb.moverange = moverange;
					lb.aTargets = aPlayers;
					lb.tmpx = u.xpos;
					lb.tmpy = u.ypos;
					bonusLayer.addChild(lb);
					break;
				case UnitType.EnergyBonus:
					var eb:EnergyBonus = new EnergyBonus();
					eb.dimension = bonusLayer;
					eb.moverange = moverange;
					eb.aTargets = aPlayers;
					eb.tmpx = u.xpos;
					eb.tmpy = u.ypos;
					bonusLayer.addChild(eb);
					break;
				case UnitType.MissileBonus :
					var mb:MissileBonus = new MissileBonus();
					mb.dimension = bonusLayer;
					mb.moverange = moverange;
					mb.aTargets = aPlayers;
					mb.tmpx = u.xpos;
					mb.tmpy = u.ypos;
					bonusLayer.addChild(mb);
					break;
				case UnitType.BulletBonus :
					var bb:BulletBonus = new BulletBonus();
					bb.dimension = bonusLayer;
					bb.moverange = moverange;
					bb.aTargets = aPlayers;
					bb.tmpx = u.xpos;
					bb.tmpy = u.ypos;
					bonusLayer.addChild(bb);
					break;
					//Boss
				case UnitType.Osprey :
					var osprey:Osprey = new Osprey();
					osprey.dimension = skyLayer;
					osprey.bulletLayer = bulletLayer;
					osprey.moverange = moverange;
					osprey.aFriends = aEnemies;
					osprey.aTargets = aPlayers;
					osprey.x = u.xpos;
					osprey.y = u.ypos;
					skyLayer.addChild(osprey);
					aEnemies.push(osprey);
					break;
				case UnitType.Poseidon :
					var poseidon:Poseidon = new Poseidon();
					poseidon.dimension = skyLayer;
					poseidon.bulletLayer = bulletLayer;
					poseidon.moverange = moverange;
					poseidon.aFriends = aEnemies;
					poseidon.aTargets = aPlayers;
					poseidon.x = u.xpos;
					poseidon.y = u.ypos;
					skyLayer.addChild(poseidon);
					aEnemies.push(poseidon);
					break;
			}
		}
	}
}